<template>
  <div class="app-container">
    <pro-table
      ref="tableRef"
      :columns="columns"
      :data="tableData"
      :loading="loading"
      :total="total"
      @query="handleQuery"
      @add="handleAdd"
      @batch-delete="handleBatchDelete"
      @selection-change="handleSelectionChange"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      @refresh="getList"
    >
      <template #action="{ row }">
        <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
        <el-button type="success" link @click="handlePermission(row)">权限设置</el-button>
        <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
      </template>
    </pro-table>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="500px"
      destroy-on-close
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input v-model="form.code" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="form.description"
            type="textarea"
            placeholder="请输入描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitForm">确 定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 权限设置弹窗 -->
    <el-dialog
      v-model="permissionDialogVisible"
      title="权限设置"
      width="600px"
    >
      <el-tabs v-model="activePermissionTab">
        <el-tab-pane label="菜单权限" name="menu">
          <el-tree
            ref="menuTreeRef"
            :data="menuTree"
            show-checkbox
            node-key="id"
            :props="{ label: 'title' }"
            :default-checked-keys="selectedMenus"
          />
        </el-tab-pane>
        <el-tab-pane label="数据权限" name="data">
          <el-form :model="dataPermissionForm" label-width="100px">
            <el-form-item label="数据范围">
              <el-select v-model="dataPermissionForm.dataScope" style="width: 100%">
                <el-option label="全部数据权限" value="1" />
                <el-option label="本部门数据权限" value="2" />
                <el-option label="本部门及以下数据权限" value="3" />
                <el-option label="仅本人数据权限" value="4" />
                <el-option label="自定义数据权限" value="5" />
              </el-select>
            </el-form-item>
            <el-form-item 
              label="数据权限" 
              v-if="dataPermissionForm.dataScope === '5'"
            >
              <el-tree
                ref="deptTreeRef"
                :data="deptTree"
                show-checkbox
                node-key="id"
                :props="{ label: 'name' }"
                :default-checked-keys="selectedDepts"
              />
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitPermission">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search, Refresh, Plus, Delete
} from '@element-plus/icons-vue'
import { 
  getRoleList, 
  addRole, 
  updateRole, 
  deleteRole,
  updateRoleStatus, 
  getRolePermissions, 
  assignRolePermissions
} from '@/api'
import ProTable from '@/components/ProTable/index.vue';

// 列配置
const columns = [
  {
    prop: 'name',
    label: '角色名称',
    width: '150',
    search: true // 显示在搜索区域
  },
  {
    prop: 'code',
    label: '角色编码',
    width: '150',
    search: true
  },
  {
    prop: 'description',
    label: '描述',
    tooltip: true
  },
  {
    prop: 'status',
    label: '状态',
    width: '100',
    align: 'center',
    search: true,
    searchType: 'select',
    options: [
      { label: '启用', value: '1' },
      { label: '禁用', value: '0' }
    ],
    render: 'StatusSwitch' // 自定义渲染组件
  },
  {
    prop: 'createTime',
    label: '创建时间',
    width: '180',
    search: true,
    searchType: 'daterange'
  }
]

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: '',
  code: '',
  status: ''
})

// 表格数据
const loading = ref(false)
const tableData = ref([])
const total = ref(0)
const selectedRows = ref([])

// 表单相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = ref({
  name: '',
  code: '',
  status: 1,
  description: ''
})

const rules = {
  name: [
    { required: true, message: '请输入角色名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入角色编码', trigger: 'blur' },
    { pattern: /^[A-Z_]{2,20}$/, message: '角色编码只能包含大写字母和下划线', trigger: 'blur' }
  ]
}

// 权限设置相关
const permissionDialogVisible = ref(false)
const activePermissionTab = ref('menu')
const menuTreeRef = ref(null)
const deptTreeRef = ref(null)
const menuTree = ref([])
const deptTree = ref([])
const selectedMenus = ref([])
const selectedDepts = ref([])
const currentRoleId = ref(null)
const dataPermissionForm = ref({
  dataScope: '1'
})

// 获取列表数据
const getList = async (params) => {
  loading.value = true
  try {
    const res = await getRoleList(params)
    tableData.value = res.data.items
    total.value = res.data.total
  } catch (error) {
    console.error('获取列表失败:', error)
  } finally {
    loading.value = false
  }
}

// 查询操作
const handleQuery = () => {
  queryParams.value.pageNum = 1
  getList(queryParams.value)
}

// 重置查询
const resetQuery = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    name: '',
    code: '',
    status: ''
  }
  getList(queryParams.value)
}

// 表格选择
const handleSelectionChange = (selection) => {
  selectedRows.value = selection
}

// 刷新列表
const refreshList = () => {
  getList(queryParams.value)
}

// 新增角色
const handleAdd = () => {
  dialogType.value = 'add'
  form.value = {
    name: '',
    code: '',
    status: 1,
    description: ''
  }
  dialogVisible.value = true
}

// 编辑角色
const handleEdit = (row) => {
  dialogType.value = 'edit'
  form.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addRole(form.value)
          ElMessage.success('添加成功')
        } else {
          await updateRole(form.value)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        getList(queryParams.value)
      } catch (error) {
        console.error('提交失败:', error)
      }
    }
  })
}

// 删除角色
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除该角色吗？',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteRole(row.id)
      ElMessage.success('删除成功')
      getList(queryParams.value)
    } catch (error) {
      console.error('删除失败:', error)
    }
  })
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRows.value.length) {
    ElMessage.warning('请选择要删除的数据')
    return
  }
  
  ElMessageBox.confirm(
    `确认删除选中的 ${selectedRows.value.length} 条数据吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const ids = selectedRows.value.map(row => row.id)
      await deleteRole(ids)
      ElMessage.success('批量删除成功')
      getList(queryParams.value)
    } catch (error) {
      console.error('批量删除失败:', error)
    }
  })
}

// 状态更改
const handleStatusChange = async (row) => {
  try {
    await updateRoleStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    row.status = row.status === 1 ? 0 : 1 // 恢复原状态
  }
}

// 权限设置
const handlePermission = async (row) => {
  currentRoleId.value = row.id
  try {
    const res = await getRolePermissions(row.id)
    selectedMenus.value = res.data.menuIds
    selectedDepts.value = res.data.deptIds
    dataPermissionForm.value.dataScope = res.data.dataScope
    permissionDialogVisible.value = true
  } catch (error) {
    console.error('获取权限数据失败:', error)
  }
}

// 提交权限设置
const submitPermission = async () => {
  try {
    await assignRolePermissions({
      roleId: currentRoleId.value,
      menuIds: menuTreeRef.value.getCheckedKeys(),
      deptIds: dataPermissionForm.value.dataScope === '5' 
        ? deptTreeRef.value.getCheckedKeys() 
        : [],
      dataScope: dataPermissionForm.value.dataScope
    })
    ElMessage.success('权限设置成功')
    permissionDialogVisible.value = false
  } catch (error) {
    console.error('权限设置失败:', error)
  }
}

// 分页
const handleSizeChange = (val) => {
  queryParams.value.pageSize = val
  getList(queryParams.value)
}

const handleCurrentChange = (val) => {
  queryParams.value.pageNum = val
  getList(queryParams.value)
}

onMounted(() => {
  getList(queryParams.value)
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.search-wrapper {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-wrapper {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.left {
  display: flex;
  gap: 10px;
}

.right {
  display: flex;
  gap: 10px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-tree) {
  margin: 10px 0;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 10px;
}

:deep(.el-card__header) {
  padding: 15px 20px;
}

:deep(.el-form--inline .el-form-item) {
  margin-right: 0;
}
</style> 